let $;
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate'], function (exports) {
    $ = layui.$;
    let layer = layui.layer;
    let table = layui.table;
    let form = layui.form;
    let layDate = layui.laydate;
    let laytpl = layui.laytpl;
    let formSelects = layui.formSelects;
    let servCategIds;
    let categOneIds;
    let categIds;
    let companyId;
    let cityIds;
    let channelIds;
    let productIds;
    let expiryType;
    // let channeRate = 0;
    zmnLayUtil.layFormVerify(form);
    var companyTableCols = [
        [
            {field: 'value', type: 'checkbox', fixed: 'left', width: 50, align: 'center'},
            {field: 'text', title: '全部', align: 'center'}
        ]
    ];

    // var channelTableCols = [
    //     [
    //         {field: 'typeId', type: 'checkbox', fixed: 'left', width: 50, align: 'center'},
    //         {field: 'name', title: '全部', align: 'center'}
    //     ]
    // ];

    /**
     * 描述: 优惠券使用时间初始化
     **/
    layDate.render({
        elem: '#startAndEndDate',
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        range: true
    });
    /**
     * 描述: 发放有效期时间初始化
     **/
    layDate.render({
        elem: '#issueTime',
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        range: true
    });
    var updateInit = function(){
        var coupBatch = json.coupBatch;
        if (coupBatch && coupBatch.batchId){
            coupBatch.number = "不限";
            coupBatch.startAndEndDate = zmnUtil.createTime(coupBatch.usefulLifeBegin) + " - " + zmnUtil.createTime(coupBatch.usefulLifeEnd);
            if (coupBatch.preferentialType) {
                var unit = "";
                if (coupBatch.preferentialType == 1) {
                    unit = "折";
                    coupBatch.preferentialValue = coupBatch.preferentialValue/10;
                    $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|coupDiscount");
                }else {
                    unit = "元";
                    coupBatch.preferentialValue = coupBatch.preferentialValue/100;
                    $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|amount");
                }
                form.render();
                zmnLayUtil.layFormVerify(form);

                $("#unit").html(unit);
                coupBatch.preferentialType = coupBatch.preferentialType.toString();
            }
            if (coupBatch.cityType) {
                coupBatch.cityType = coupBatch.cityType.toString();
            }
            if (coupBatch.configType) {
                coupBatch.configType = coupBatch.configType.toString();
            }
            if (coupBatch.channelConfigType) {
                coupBatch.channelConfigType = coupBatch.channelConfigType.toString();
            }
            if (coupBatch.companyType) {
                coupBatch.companyType = coupBatch.companyType.toString();
            }
            if (coupBatch.channelType) {
                coupBatch.channelType = coupBatch.channelType.toString();
            }
            if (coupBatch.serverType) {
                coupBatch.serverType = coupBatch.serverType.toString();
            }
       /*     if (coupBatch.activateWay) {
                coupBatch.activateWay = coupBatch.activateWay.toString();
            }*/
            if (coupBatch.servCategIds) {
                servCategIds = coupBatch.servCategIds;
            }
            if (coupBatch.categOneIds) {
                categOneIds = coupBatch.categOneIds;
            }
            if (coupBatch.categIds) {
                categIds = coupBatch.categIds;
            }
            if (coupBatch.companyIds) {
                companyId = coupBatch.companyIds.join(",");
            }
            if (coupBatch.cityIds) {
                cityIds = coupBatch.cityIds;
            }
            if (coupBatch.channelIds) {
                channelIds = coupBatch.channelIds;
            }
            if (coupBatch.productIds) {
                productIds = coupBatch.productIds;
            }

            // 数据库读出售价为0时表示没填写售价，返回null
            if (coupBatch.salePrice && coupBatch.salePrice !=0) {
                console.log(coupBatch.salePrice)
                coupBatch.salePrice = coupBatch.salePrice/100;
            }
            else if (coupBatch.salePrice ==0){
                coupBatch.salePrice = null;
            }
            if (coupBatch.condition) {
                coupBatch.condition = coupBatch.condition/100;
            }
            if(coupBatch.couponType){
                coupBatch.couponType=coupBatch.couponType.toString();
            }
            if (coupBatch.redeemCodeGenerate){
                coupBatch.redeemCodeGenerate = coupBatch.redeemCodeGenerate.toString()
            }
            if (coupBatch.redeemCodeNumber){
                coupBatch.redeemCodeNumber = coupBatch.redeemCodeNumber.toString()
            }
            if (coupBatch.useType){
                coupBatch.useType = coupBatch.useType.toString()
                if (coupBatch.useType == "1") {
                    $("#templateIdInput").show();
                    // $("#issueEffectiveTimeInput").show();
                    $('input[name="preferentialType"]:eq(0)').attr("disabled","true");
                }
                else{
                    //其他
                    $("#templateIdInput").hide();
                    // $("#issueEffectiveTimeInput").hide();
                }
            }
            if (coupBatch.usePlatTemplateId){
                coupBatch.usePlatTemplateId = coupBatch.usePlatTemplateId.toString()
            }
            if (coupBatch.issueTimeBegin&&coupBatch.issueTimeEnd){
                coupBatch.issueTime = zmnUtil.createTime(coupBatch.issueTimeBegin) + " - " + zmnUtil.createTime(coupBatch.issueTimeEnd);
            }
            if(coupBatch.expiryType){
                coupBatch.expiryType=coupBatch.expiryType.toString();
                //固定时长
                if(coupBatch.expiryType=="2"){
                    coupBatch.tempEffectiveDays=coupBatch.effectiveDays.toString();
                    layui.use('form', function () {
                        var form = layui.form;
                        $("#fixedDeadLineInput").show();
                        $("#expiryTypeInput").hide();
                        $("#expiryTypeInput").find($("input[name='startAndEndDate']")).attr("lay-verify","");
                        $("#useType").attr("disabled","disabled");
                        form.render();
                    })
                }
                else{
                    $("#useType").attr("disabled","");
                }
                // else{
                //     layui.use('form', function () {
                //         var form = layui.form;
                //         $("#fixedDeadLineInput").hide();
                //         $("#expiryTypeInput").show();
                //         form.render();
                //     })
                // }
            }
            //分摊比例
            // if(coupBatch.headOfficeRate){
            // $("#headOfficeRate").val= coupBatch.headOfficeRate;
            // }
            // if(coupBatch.infoCompanyRate){
            // $("#infoCompanyRate").val = coupBatch.infoCompanyRate;
            // }
            // if(coupBatch.masterRate){
            // $("#masterRate").val = coupBatch.masterRate;
            // }
            // if(coupBatch.channelRate){
            // $("#channelRate").val = coupBatch.channelRate;
            // }
            companyEcho(coupBatch.companyIds);
            cityEcho(coupBatch.batchId);
            channelEcho(coupBatch.channelIds);
            servCategEcho(coupBatch.servCategIds);
            categOneEcho(coupBatch.servCategIds,coupBatch.categOneIds);
            categTwoEcho(coupBatch.servCategIds,coupBatch.categOneIds,coupBatch.categIds);
            productEcho(coupBatch.servCategIds,coupBatch.categOneIds,coupBatch.categIds,coupBatch.productIds);
            form.val("zmn-batch-form", coupBatch);

            // 分摊比例
            var  apportionRateArray = new Array();
            apportionRateArray.push({type:1, value: parseInt(coupBatch.headOfficeRate)});
            apportionRateArray.push({type:2, value: parseInt(coupBatch.infoCompanyRate)});
            apportionRateArray.push({type:3, value: parseInt(coupBatch.masterRate)});
            apportionRateArray.push({type:4, value: parseInt(coupBatch.channelRate)});
            $("#apportionRate").val(JSON.stringify(apportionRateArray));
        } else {
            //初始化公司
            companyEcho();
            //初始化城市
            cityEcho();
            //初始化渠道
            channelEcho();
        }
    }();

    function cityEcho(batchId) {
        formSelects.data('cityTypeSelect', 'local', {
            arr: json.province,
            linkage: false
        });
            if(batchId){
                $.ajax({
                    async: false,
                    type: "POST",
                    // url: "/coup/batch/loadCityData",
                    url: "/coup/batch/loadCityData",
                    data: {batchId:batchId},
                    success:function(data) {
                        formSelects.value('cityTypeSelect',data);
                    }
                });
            }
    }
    formSelects.on('cityTypeSelect', function(id, vals, val, isAdd, isDisabled){
            if(isAdd) {
                let pid = JSON.parse(val.XM_PID_VALUE);
                let children = val.children;
                let selectdDD = $("dl[xid='cityTypeSelect'] dd[tree-id='"+pid[0]+"']");
                let childrenDD = $("dl[xid='cityTypeSelect'] dd[tree-id^='"+pid[0]+"-']");
                let allSelectedChildrenValues = new Array();
                childrenDD.each(function (index, domEle){
                    allSelectedChildrenValues.push($(domEle).attr("lay-value"));
                });
                if(children) {
                    if(selectdDD.hasClass("xm-select-this")) {
                        selectdDD.removeClass("xm-select-this");
                    } else {
                        selectdDD.addClass("xm-select-this");
                    }
                    formSelects.value('cityTypeSelect', allSelectedChildrenValues, true);
                    return false;
                } else {
                    let selectedChildrenDD = $("dl[xid='cityTypeSelect'] dd[tree-id^='"+pid[0]+"-'].xm-select-this");
                    if((selectedChildrenDD.length + 1) == childrenDD.length) {
                        selectdDD.addClass("xm-select-this");
                    }
                }
            } else {
                let children = val.children;
                if(children) {
                    let pid = JSON.parse(val.XM_PID_VALUE);
                    let childrenDD = $("dl[xid='cityTypeSelect'] dd[tree-id^='"+pid[0]+"-']");
                    let unselectedChildrenDD = new Array();
                    childrenDD.each(function (index,domEle){
                        unselectedChildrenDD.push($(domEle).attr("lay-value"));
                    });
                    formSelects.value('cityTypeSelect', unselectedChildrenDD, false);
                    return true;
                } else {
                    if(val.XM_PID_VALUE) {
                        let pid = JSON.parse(val.XM_PID_VALUE);
                        let selectdDD = $("dl[xid='cityTypeSelect'] dd[tree-id='"+pid[0]+"']");
                        selectdDD.removeClass("xm-select-this");
                    }
                }
            }
            return true;
        });
    function companyEcho(companyIds) {
        let arr = new Array();
        let selectedArray = new Array();
        let company = json.company;
        $(company).each(function(companyIndex, companyItem) {
            let companyCityItem = new Object();
            companyCityItem.name = companyItem.text;
            companyCityItem.value = companyItem.value;
            arr.push(companyCityItem);
            if(companyIds) {
                $(companyIds).each(function(companyIdIndex, companyId) {
                    if (companyItem.value == companyId){
                        //选中公司
                        selectedArray.push(companyId);
                        return false;
                    }
                });
            }
            // else{
            //     selectedArray.push(companyCityItem.value);
            // }

        });
        formSelects.data('companyTypeSelect', 'local', {
            arr: arr,
            linkage: false
        });
        formSelects.value('companyTypeSelect', selectedArray);
    }

    function channelEcho(channelIds) {
        let arr = new Array();
        let selectedArray = new Array();
        let channel = json.channelType;
        $(channel).each(function(channelIndex, channelItem) {
            let channelItemNewItem = new Object();
            channelItemNewItem.name = channelItem.name;
            channelItemNewItem.value = channelItem.typeId;
            arr.push(channelItemNewItem);
            if(channelIds) {
                $(channelIds).each(function(channelIdIndex, channelId) {
                    if (channelItemNewItem.value == channelId){
                        //选中渠道
                        selectedArray.push(channelId);
                        return false;
                    }
                });
            }
            // else{
            //     selectedArray.push(companyCityItem.value);
            // }

        });
        formSelects.data('channelTypeSelect', 'local', {
            arr: arr,
            linkage: false
        });
        formSelects.value('channelTypeSelect', selectedArray);
    }
    /**
     * 描述:回显服务
     **/
    function servCategEcho(servCategIds){
        var serverClassify = json.serverClassify;
        for (var i = 0;i<serverClassify.length;i++){
            for (var j = 0;j<servCategIds.length;j++) {
                var item = serverClassify[i].value;
                if (item == servCategIds[j]){
                    serverClassify[i].LAY_CHECKED = true;
                    break;
                }
            }
        }
        json.serverClassify = serverClassify;
        serverTableRender();
    }

    /**
     * 描述:回显服务
     **/
    function categOneEcho(servCategIds,categOneIds){
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: "/coup/batch/loadCategOneData",
            data: JSON.stringify({servCategIds:servCategIds}),
            dataType: 'json',
            success: function(data) {
                if (categOneIds) {
                    for (var i = 0;i<data.length;i++){
                        for (var j = 0;j<categOneIds.length;j++) {
                            var item = data[i].value;
                            if (item == categOneIds[j]){
                                data[i].LAY_CHECKED = true;
                                break;
                            }
                        }
                    }
                }
                json.cateOne = data;
                oneTableRender();
            }
        });
    }

    /**
     * 描述:回显服务
     **/
    function categTwoEcho(servCategIds,categOneIds,categIds){
        if (categOneIds) {
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "/coup/batch/loadCategTwoData",
                data: JSON.stringify({servCategIds:servCategIds,categOneIds:categOneIds}),
                dataType: 'json',
                success: function(data) {
                    if (categIds) {
                        for (var i = 0;i<data.length;i++){
                            for (var j = 0;j<categIds.length;j++) {
                                var item = data[i].value;
                                if (item == categIds[j]){
                                    data[i].LAY_CHECKED = true;
                                    break;
                                }
                            }
                        }
                    }
                    json.cateTwo = data;
                    twoTableRender();
                }
            });
        }

    }

    /**
     * 描述:回显服务
     **/
    function productEcho(servCategIds,categOneIds,categIds,productIds){
        if (categOneIds && categIds) {
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "/coup/batch/loadProductData",
                data: JSON.stringify({servCategIds:servCategIds,categOneIds:categOneIds,categIds:categIds}),
                dataType: 'json',
                success: function(data) {
                    if (productIds) {
                        for (var i = 0;i<data.length;i++){
                            for (var j = 0;j<productIds.length;j++) {
                                var item = data[i].value;
                                if (item == productIds[j]){
                                    data[i].LAY_CHECKED = true;
                                    break;
                                }
                            }
                        }
                    }
                    json.product = data;
                    productTableRender();
                }
            });
        }
    }


    /**
     * 描述: 表单初始化
     **/
    form.render();
    /**
     * 描述: 修改固定时长时，加上固定时长的非空判断和去掉固定期限的非空判断
     **/
    $("#fixedDeadLineInput").find($("input[name='tempEffectiveDays']")).blur(function () {
        $("#fixedDeadLineInput").find($("input[name='tempEffectiveDays']")).attr("lay-verify","required");
        $("#expiryTypeInput").find($("input[name='startAndEndDate']")).attr("lay-verify","");
    });
    // $("#fixedDeadLineInput").find($("input[name='startAndEndDate']")).blur(function () {
    //     $("#fixedDeadLineInput").find($("input[name='startAndEndDate']")).attr("lay-verify","required");
    //     $("#expiryTypeInput").find($("input[name='tempEffectiveDays']")).attr("lay-verify","");
    // });
    /**
     * 描述: 表单提交事件
     **/
    form.on('submit(zmn-batch-form-submit)', function (obj) {


        let cityValues = formSelects.value('cityTypeSelect');
        let companyValues = formSelects.value('companyTypeSelect');
        let channelValues =  formSelects.value('channelTypeSelect');
        let companyIdArray = new Array();
        let cityIdArray = new Array();
        let channelArray = new Array();
        $(cityValues).each(function(index, item) {
            let cityId = parseInt(item.value);
            if(cityIdArray.indexOf(cityId) <= -1) {
                cityIdArray.push(cityId);
            }
        });
        $(companyValues).each(function(index, item) {
            let companyId = parseInt(item.value);
            if(companyIdArray.indexOf(companyId) <= -1) {
                companyIdArray.push(companyId);
            }
        });
        $(channelValues).each(function(index, item) {
            let channelId = parseInt(item.value);
            if(channelArray.indexOf(channelId) <= -1) {
                channelArray.push(channelId);
            }
        });

        if(companyIdArray.length == 0) {
            layer.msg("请选择公司条件");
            return false;
        }

        if(cityIdArray.length == 0) {
            layer.msg("请选择城市条件");
            return false;
        }

        if(channelArray.length == 0) {
            layer.msg("请选择渠道条件");
            return false;
        }

        var param = obj.field;
        param.companyIds = companyIdArray;
        param.cityIds = cityIdArray;
        param.channelIds = channelArray;
        param.costDeptId = json.deptId;
        param.costDeptName = json.deptName;
        param.number = 0;
        var apportionRate = JSON.parse(param.apportionRate);
        param.headOfficeRate=parseInt(apportionRate[0].value);
        param.infoCompanyRate=parseInt(apportionRate[1].value);
        param.masterRate=parseInt(apportionRate[2].value);
        var apportionChannelRate = JSON.parse(param.apportionChannelRate);
        param.channelRate=parseInt(apportionChannelRate[0].value);
        if (param.note && param.note.length > 200){
            layer.msg("备注不能超过200字符");
            return false;
        }
        // 检验公司参数
        // if (!companyId){
        //     layer.msg("请选择公司条件");
        //     return false;
        // }else {
        //     param.companyIds = companyId.split(",");
        // }

        // 城市不为空添加城市参数
        // var cityCheckData = table.checkStatus('zmn-city-table').data;
        //
        // if (cityCheckData.length >0){
        //     var arr = new Array();
        //     for (var i = 0;i<cityCheckData.length;i++){
        //         arr.push(cityCheckData[i].value)
        //     }
        //     param.cityIds = arr;
        // }else if (cityIds) {
        //     param.cityIds = cityIds;
        // }else {
        //     layer.msg("请选择城市条件");
        //     return false;
        // }

        // 检查渠道参数
        // var channelCheckData = table.checkStatus('zmn-channel-table').data;
        // if (channelCheckData.length > 0){
        //     var arr = new Array();
        //     for (var i = 0;i<channelCheckData.length;i++){
        //         arr.push(channelCheckData[i].typeId)
        //     }
        //     param.channelIds = arr;
        // } else if (channelIds){
        //     param.channelIds = channelIds;
        // } else {
        //     layer.msg("请选择渠道条件");
        //     return false;
        // }
        //是否全选
        if(param.channelIds.length == json.channelType.length){
            //全选
            param.channelSelectedType=2;
        }
        else{
            //没全选
            param.channelSelectedType=1;
        }
        param.citySelectedType=2;
        param.productSelectedType=2;
        // 检查服务产品参数
        if (!servCategIds){
            layer.msg("请选择服务条件");
            return false;
        } else {
            param.servCategIds = servCategIds;
            param.categOneIds = categOneIds;
            param.categIds = categIds;
            var productCheckData = table.checkStatus('zmn-product-table').data;
            if (productCheckData.length > 0){
                var arr = new Array();
                for (var i = 0;i<productCheckData.length;i++){
                    arr.push(productCheckData[i].value)
                }
                param.productIds = arr;
            }else if (productIds) {
                param.productIds = productIds;
            }
        }
        // if (!param.activateWay) {
        //     layer.msg("请选择激活方式");
        //     return false;
        // }
        param.preferentialValueFormat = param.preferentialValue;
        param.salePriceFormat = param.salePrice;
        param.conditionFormat = param.condition;
        param.preferentialValue = null;
        param.salePrice = null;
        param.condition = null;

        $("#submit").prop("disabled", true);
        $.ajax({
            type: "POST",
            url: "/coup/batch/addEdit.action",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(param),
            success: function (json) {
                if (json.status == 200) {
                    zmnLayUtil.closeThisIframeMsg(parent, json.message, "zmn-coup-table");
                    parent.location.reload(true);
                }
                layer.msg(json.message);
            }
        });
        $("#submit").prop("disabled", false);
        return false;
    });


    /**
     * 描述: 监听优惠方式 更改折扣单位
     **/
    form.on("radio(preferentialType)",function (data) {
        if (data.value == 1) {
            $("#unit").html("折") ;
            $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|coupDiscount");
        }else {
            $("#unit").html("元") ;
            $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|amount");
        }
        form.render();
        zmnLayUtil.layFormVerify(form);
    });

    /**
     * 描述:监听公司表格复选框事件
     **/
    table.on('checkbox(zmn-table)',function(){
        var checkData = table.checkStatus('zmn-table').data;
        if (checkData.length == 0){
            json.city = [];
            cityTableRender();
        }else if (checkData.length > 0) {
            companyId = "";
            for (var i = 0;i<checkData.length;i++){
                if (companyId){
                    companyId += ","+checkData[i].value;
                } else {
                    companyId += checkData[i].value;
                }
            }
            $.post("/coup/batch/loadCityData",{companyId:companyId},function (data) {
                json.city = data;
                cityTableRender();
            })
        }
    });
    /**
     * 描述:监听批次使用类型
     **/
    form.on("radio(useType)",function (data,row) {

        // 支付宝无资金
        if (data.value == 1) {
            $("#templateIdInput").show();
            $('input[name="preferentialType"]:eq(0)').attr("disabled","true");
            $('input[name="preferentialType"]:eq(1)').trigger('click');
            $("#unit").html("元") ;
            $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|amount");

            $('input[name="expiryType"]:eq(0)').trigger('click');
            form.render();
        }
        else{
            //其他
            $("#templateIdInput").hide();
            $('input[name="preferentialType"]:eq(0)').removeAttr("disabled");
            form.render();
        }
    })

    /**
     * 描述: 服务产品 选择条件
     **/
    form.on("radio(server)",function (data) {
        //页面层
        layer.open({
            type: 1,
            title: false,
            btn:['确定'],
            area: ['800px', '500px'],
            content: '<div class="layui-row">\n' +
                '    <div class="layui-col-sm3 layui-col-md3">\n' +
                '        <div class="layui-card-header" style="text-align: center"><b>服务</b></div>\n' +
                '        <div style="height:380px;overflow-y: auto ;clear: both;">\n' +
                '            <table class="layui-hide" id="zmn-server-table" lay-filter="zmn-server-table"></table>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '    <div class="layui-col-sm3 layui-col-md3">\n' +
                '        <div class="layui-card-header" style="text-align: center"><b>一级分类</b></div>\n' +
                '        <div style="height:380px;overflow-y: auto ;clear: both;">\n' +
                '            <table class="layui-hide" id="zmn-one-table" lay-filter="zmn-one-table"></table>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '    <div class="layui-col-sm3 layui-col-md3">\n' +
                '        <div class="layui-card-header" style="text-align: center"><b>二级分类</b></div>\n' +
                '        <div style="height:380px;overflow-y: auto ;clear: both;">\n' +
                '            <table class="layui-hide" id="zmn-two-table" lay-filter="zmn-two-table"></table>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '    <div class="layui-col-sm3 layui-col-md3">\n' +
                '        <div class="layui-card-header" style="text-align: center"><b>产品</b></div>\n' +
                '        <div style="height:380px;overflow-y: auto ;clear: both;">\n' +
                '            <table class="layui-hide" id="zmn-product-table" lay-filter="zmn-product-table"></table>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '</div>'
        });
        serverTableRender();
        oneTableRender();
        twoTableRender();
        productTableRender();
    });

    /**
     * 描述:监听服务产品表格复选框事件
     **/
    table.on('checkbox(zmn-server-table)',function(){
        var checkData = table.checkStatus('zmn-server-table').data;
        if (checkData.length == 0){
            servCategIds = [];
            categOneIds = [];
            categIds = [];
            productIds = [];
            json.cateOne = [];
            oneTableRender();
            json.product = [];
            json.cateTwo = [];
            twoTableRender();
            productTableRender();
        }else if (checkData.length > 0) {
            servCategIds = new Array();
            for (var i = 0;i<checkData.length;i++){
                servCategIds.push(checkData[i].value)
            }
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "/coup/batch/loadCategOneData",
                data: JSON.stringify({servCategIds:servCategIds}),
                dataType: 'json',
                success: function(data) {
                    json.cateOne = data;
                    oneTableRender();
                }
            });
            categOneIds = [];
            categIds = [];
            productIds = [];
            json.product = [];
            json.cateTwo = [];
            twoTableRender();
            productTableRender();
        }
    });

    /**
     * 描述:监听服务产品表格复选框事件
     **/
    table.on('checkbox(zmn-one-table)',function(){
        var checkData = table.checkStatus('zmn-one-table').data;
        if (checkData.length == 0){
            categOneIds = [];
            categIds = [];
            productIds = [];
            json.cateTwo = [];
            twoTableRender();
            json.product = [];
            productTableRender();
        }else if (checkData.length > 0) {
            categOneIds = new Array();
            for (var i = 0;i<checkData.length;i++){
                categOneIds.push(checkData[i].value)
            }
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "/coup/batch/loadCategTwoData",
                data: JSON.stringify({servCategIds:servCategIds,categOneIds:categOneIds}),
                dataType: 'json',
                success: function(data) {
                    json.cateTwo = data;
                    twoTableRender();
                }
            });
            categIds = [];
            productIds = [];
            json.product = [];
            productTableRender();
        }
    });

    /**
     * 描述:监听服务产品表格复选框事件
     **/
    table.on('checkbox(zmn-two-table)',function(){
        var checkData = table.checkStatus('zmn-two-table').data;
        if (checkData.length == 0){
            categIds = [];
            productIds = [];
            json.product = [];
            productTableRender();
        }else if (checkData.length > 0) {
            categIds = new Array();
            for (var i = 0;i<checkData.length;i++){
                categIds.push(checkData[i].value)
            }
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                url: "/coup/batch/loadProductData",
                data: JSON.stringify({servCategIds:servCategIds,categOneIds:categOneIds,categIds:categIds}),
                dataType: 'json',
                success: function(data) {
                    json.product = data;
                    productTableRender();
                }
            });
            productIds = [];
        }
    });

    /**
     * 描述:监听服务产品表格复选框事件
     **/
    table.on('checkbox(zmn-product-table)',function(){
        var checkData = table.checkStatus('zmn-product-table').data;
        if (checkData.length == 0){
            productIds = [];
        }
    });


    function serverTableRender(){
        table.render({
            elem: "#zmn-server-table",
            data: json.serverClassify,
            limit: json.serverClassify.length,
            cols: companyTableCols,
            height: null
        });
    }

    function oneTableRender(){
        table.render({
            elem: "#zmn-one-table",
            data: json.cateOne,
            limit: json.cateOne.length,
            cols: companyTableCols,
            height: null
        });
    }

    function twoTableRender(){
        table.render({
            elem: "#zmn-two-table",
            data: json.cateTwo,
            limit: json.cateTwo.length,
            cols: companyTableCols,
            height: null
        });
    }

    function productTableRender(){
        table.render({
            elem: "#zmn-product-table",
            data: json.product,
            limit: json.product.length,
            cols: companyTableCols,
            height: null
        });
    }

    function cityTableRender(){
        table.render({
            elem: "#zmn-city-table",
            data: json.city,
            limit: json.city.length,
            cols: companyTableCols,
            height: null
        });
    }


    //点击取消
    $(document).on('click', '#cancel', function () {
        zmnLayUtil.closeThisIframe(parent);
    });

    $(document).on('click', '#addApportion', function () {
        let apportionRateJson = $("#apportionRate").val();
        let apportionRate = JSON.parse(apportionRateJson);
        // var coupBatch = json.coupBatch;
        // if (coupBatch.batchId) {
        //     let apportionRateArray = new Array();
        //     var value;
        //     for (var i = 1; i <5 ; i++) {
        //           if(i==1){
        //               value = coupBatch.
        //           }
        //         apportionRateArray.push({type:i, value: parseInt(value)});
        //     }
        //
        //     $("#apportionRate").val(JSON.stringify(apportionRateArray));
        // }
        laytpl(addApportionContent.innerHTML).render(apportionRate, function (html) {
            // console.log(html);
            var contentl;
            var index=  layer.open({
                title: "配置比例"
                ,content: html
                ,btn: ['确定']
                ,btnAlign: 'c'
                   ,success: function () {
                    var coupBatch = json.coupBatch;
                    // var value = $("input[name=configType]:checked").val();
                    // 订单分润只配置渠道比例，只设置渠道比例可编辑
                    // if (value == 1) {
                    //     $("#infoCompanyRate").attr("disabled","true");
                    //     $("#infoCompanyRate").css("background-color","#EEEEEE");
                    //     $("#masterRate").attr("disabled","true");
                    //     $("#masterRate").css("background-color","#EEEEEE");
                    // }
                    $(".apportionRateVal").each(function () {
                        var id=this.id;
                        if(id=='headOfficeRate'){
                            if(coupBatch.headOfficeRate){
                                this.value=coupBatch.headOfficeRate;
                            }
                        }
                        if(id=='infoCompanyRate'){
                            if(coupBatch.infoCompanyRate){
                                this.value=coupBatch.infoCompanyRate;
                            }
                        }
                        if(id=='masterRate'){
                            if(coupBatch.masterRate){
                                this.value=coupBatch.masterRate;
                            }

                        }
                    });
                    if (coupBatch.channelRate) {
                        $(".channelRateVal").val(coupBatch.channelRate);
                    }
                }
                ,yes: function(index, layero){
                    let apportionRateArrayTemp = new Array();
                    $(".apportionRateVal").each(function (index, elem) {
                        let type = $(elem).attr("data-type");
                        let value = $(elem).val();
                        apportionRateArrayTemp.push({type:parseInt(type), value: parseInt(value)});
                    });
                    apportionRateArrayTemp.push({type:4,value:parseInt($(".channelRateVal").val())})
                    $("#apportionRate").val(JSON.stringify(apportionRateArrayTemp));
                     layer.close(index);
                }
            });
        });

    });

    form.on("radio(expiryType)",function (data) {
        // if (data.value=="2"){
        //     $('input[name="useType"]:eq(1)').trigger('click');
        //     form.render();
        // }
        laytpl(expiryTypeContent.innerHTML).render(data, function (html) {
            // console.info(data)
            if(data.value=="1"){
                $("#fixedDeadLineInput").hide();
                $("#expiryTypeInput").show();
            }
            else{
                $('input[name="useType"]:eq(1)').trigger('click');
                form.render();
            }
            $('#expiryTypeInput').html(html);
            layDate.render({
                elem: '#startAndEndDate',
                format: 'yyyy-MM-dd HH:mm:ss',
                type: 'datetime',
                range: true
            });
        });
    });

    $(document).on('input propertychange', '.apportionRateVal', function () {
        let val = parseInt($(this).val());
        if(isNaN(val)) {
            val = 0;
        }
        if(val < 0) {
            $(this).val(0);
            val = 0;
        }
        let currentType = $(this).attr("data-type");
        let otherRate = 0;
        $(".apportionRateVal").each(function (index, elem) {
            let type = parseInt($(elem).attr("data-type"));
            if(type != 1 && type != currentType) {
                otherRate+=parseInt($(elem).val());
            }
        });
        let headOfficeRate = $("input[data-type='1'].apportionRateVal");
        if(val+otherRate > 100) {
            $(this).val(100-otherRate);
            headOfficeRate.val(0);
        } else {
            headOfficeRate.val(100-otherRate-val);
        }
    });

    $(document).on('input propertychange', '.channelRateVal', function (data) {
        var value = $(".channelRateVal").val();
        if(value> 100 || value<0) {
            $(this).val(100);
            channelRate.val(0);
        }
    });

    $(document).on('blur', '.apportionRateVal', function () {
        let val = parseInt($(this).val());
        if(isNaN(val)) {
            $(this).val(0);
        }
    });
    //对外暴露的接口
    exports('batch_edit', {});
});
